﻿@{
    ViewData["Title"] = "PermissionShow";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div style="margin:60px 60px">
    <label class="layui-form-label">功能名称：</label>
    <div class="layui-input-inline">
        <div class="layui-form layui-row layui-col-space16">
            <div class="layui-col-md6" style="width:300px">
                <select id="functionName">
                    <option value="">请选择</option>
                </select>
            </div>
        </div>
    </div>
    @* <button type="button" class="layui-btn layui-btn-primary" id="sea2rchBtn"><i class="layui-icon"></i> 搜 索</button> *@

    <div class="layui-inline">
        <button type="button" class="layui-btn" onclick="onAddBtn()">增加功能</button>
    </div>

    <div class="layui-inline">
        <a class="layui-btn layui-btn-danger layui-btn-normal delAll_btn">批量删除</a>
    </div>

    <table id="ID-table-demo-setRowChecked"></table>

    <div id="pagesbox"></div>

    <!--添加的弹出层-->
    <div id="add-main" style="display: none;">
        <div>
            <div style="float:left;margin-left:20px">
                <span id="Id" style="display:none"></span>
                <label id="BindId">menuName</label>
            </div>
            @* <label id="newid">newmenuName</label> *@
            <div style="float:left;margin-left:20px" id="ID-tree-demo-showCheckbox"></div>

            <input type="hidden" name="permissionId" />
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="saves">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary" id="closeBtn">重置</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        layui.use(['table', 'laypage', 'layer', 'form'], function () {
            var table = layui.table;
            var laypage = layui.laypage;
            var $ = layui.jquery;
            var form = layui.form;
            var layer = layui.layer; // 添加layui弹出层模块


            var checkedIds = []; // 存储选中节点的 id
            var checkedIdsAll = [];
            var pageSize = 15; // 每页显示条数
            //获取列表  显示
            function getListData(pageIndex) {
                //获取查询条件
                var RoleName = $('#RoleName').val();
                //ajax后台交互
                $.ajax({
                        //http://10.31.60.18:8000/AuthorizationPeopleGetRout/api
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleGetRout/api/Permission/ShowPagePermission',
                    type: 'get',
                    dataType: 'json',
                    //参数
                    data: {
                        pageIndex: pageIndex,
                        pageSize: pageSize,
                        FunctionName: $("#functionName").val(),
                    },
                    success: function (res) {
                        //渲染表格数据
                        layui.use(['table', 'laypage'], function () {
                            var table = layui.table;
                            var laypage = layui.laypage;

                            table.render({
                                //挂载的表格id
                                elem: '#ID-table-demo-setRowChecked',
                                cols: [[
                                    { type: 'checkbox', width: 60, fixed: 'center', unresize: true, align: 'center' },
                                    { field: 'functionName', title: '功能', width: 120, align: 'center' },
                                    { field: 'operation', title: '操作', width: 120, align: 'center' },
                                    { field: 'pName', title: '角色', width: 120, align: 'center' },
                                    { title: '操作', width: 120, align: 'center', templet: '#barDemo', fixed: 'right', unresize: true },

                                ]],
                                data: res.data
                            });

                            //分页
                            laypage.render({
                                //挂载的分页id
                                elem: 'pagesbox',
                                count: res.tatalCount,
                                limit: pageSize,
                                curr: pageIndex,
                                layout: ['count', 'prev', 'page', 'next', 'skip'],
                                jump: function (obj, first) {
                                    if (!first) {
                                        getListData(obj.curr);
                                    }
                                }
                            });
                        });
                    }
                });
            }

            //添加角色权限关系表 // 监听表单提交
            form.on('submit(saves)', function (data) {
                if (checkedIds.length == 0) {
                    layer.alert('至少选择一项角色信息');
                    return;
                }

                var formData = {
                    list: checkedIds,
                    menuid: $("#Id").text(),
                };
                $.ajax({
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleSetRout/api/Menu/AddMenuRole', // 替换为您的后端API接口地址
                    type: 'post',
                    data: JSON.stringify(formData),
                    contentType: 'application/json',
                    success: function (res) {
                        if (res > 0) {
                            //示范对话框所有内置图标
                            layer.alert('分配成功')
                            location.href = '/Permission/PermissionShow'
                        } else {
                            //layer.msg(res.msg, { icon: 2 });
                            layer.alert("分配失败！");
                        }
                    },
                    error: function () {
                        layer.msg('网络错误，请稍后重试', { icon: 2 });
                    }
                });
                return false; // 阻止表单跳转
            });

            $('#searchBtn').on('click', function () {
                getListData(1);
            });

            $(function () {
                // 初始化加载数据
                getListData(1);
            })

            // 监听表单提交
            form.on('submit(save)', function (data) {

                var formData = {
                    RoleName: $("#roleName").val(),
                    RoleRemark: $("#roleRemark").val(),
                    // NewEarTag: $("input[name='newEarTag']").val(),
                    // Reason: $("#reasonsAdd").val(),
                    CreateBy: "张三",
                    CreateDate: Date.now,
                };

                $.ajax({
                        //http://10.31.60.18:8000/AuthorizationPeopleGetRout/api
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleSetRout/api/Employee/AddRole', // 替换为您的后端API接口地址
                    type: 'post',
                    data: JSON.stringify(formData),
                    contentType: 'application/json',
                    success: function (res) {
                        //console.log(res);
                        if (res > 0) {
                            alert("添加成功！");
                            location.href = '/Role/ShowRole'
                            // layer.msg(res.msg, {icon: 1 });
                            // setTimeout(function () {
                            //     location.href = '/Role/ShowRole'
                            // }, 1000)
                        } else {
                            //layer.msg(res.msg, { icon: 2 });
                            alert("添加失败！");
                        }
                    },
                    error: function () {
                        layer.msg('网络错误，请稍后重试', { icon: 2 });
                    }
                });
                return false; // 阻止表单跳转
            });

            // 重置按钮点击事件
            $('#closeBtn').on('click', function () {
                layer.closeAll();
            });

            // 单删除
            function deleteData(permissionId) {
                $.ajax({
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleSetRout/api/Permission/FalseDelete?Id=' + permissionId,
                    type: 'delete',
                    success: function (res) {
                        if (res > 0) {
                            layer.msg('删除成功');
                            getListData(1);
                        } else {
                            layer.msg('删除失败');
                            getListData(1);
                        }
                    },
                    error: function () {
                        layer.msg('删除请求失败');
                    }
                });

            }

            // 监听工具条，实现删除功能
            table.on('tool(ID-table-demo-setRowChecked)', function (obj) {
                var data = obj.data;
                if (obj.event == 'edit') {
                    editData(data.permissionId, data.functionName); // 传递正确的数据项ID进行编辑操作
                }

                if (obj.event == 'delete') {
                    layer.confirm('确定删除吗？', function (index) {
                        deleteData(data.permissionId); // 传递正确的数据项ID
                        layer.close(index);
                    });
                }
            });

            // 批量删除
            $(".delAll_btn").click(function () {
                var checkStatus = table.checkStatus('ID-table-demo-setRowChecked'),
                    data = checkStatus.data,
                    permissionId = "";
                if (data.length > 0) {
                    for (var i in data) {
                        permissionId += data[i].permissionId + ",";
                    }
                    permissionId = permissionId.substring(0, permissionId.length - 1);
                    layer.confirm('确定删除选中的记录？', { icon: 3, title: '提示信息' }, function (index) {
                        $.ajax({
                            url:'http://10.31.60.18:8000/AuthorizationPeopleSetRout/api/Permission/AllFalseDelete?Id=' + permissionId,
                            type: 'put',
                            success: function (res) {
                                if (res > 0) {
                                    layer.msg("批量删除成功");
                                    getListData(1);
                                } else {
                                    layer.msg("批量删除失败");
                                }
                            },
                            error: function () {
                                layer.msg('批量删除请求失败');
                            }
                        });
                        layer.close(index);
                    });
                } else {
                    layer.msg("请选择需要删除的记录");
                }
                //console.log(checkStatus);
            });

            //绑定功能名称下拉框
            $(document).ready(function () {
                $.ajax({
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleGetRout/api/Menu/BindMenuList',
                    type: 'get',
                    dataType: 'json',
                    success: function (res) {
                        var menuList = res;
                        var select = $('#functionName');
                        $.each(menuList, function (index, item) {
                            var option = $('<option>').val(item.id).text(item.menuName);
                            select.append(option);
                        })
                        //手动触发 layui 组件的渲染
                        layui.form.render('select');
                    },
                })
            })

            //树形列表
            var tree = layui.tree;
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationPeopleGetRout/api/Menu/TreeMenuShow?Parentid=0',
                type: 'get',
                success: function (data) {
                    //console.log(data);
                    // 使用 layui 渲染树形控件
                    tree.render({
                        id: 'test',
                        elem: '#ID-tree-demo-showCheckbox',  // 容器id
                        data: data,  // 后台返回的树形数据
                        showCheckbox: true,  // 是否显示复选框
                        oncheck: function (obj) {
                            //console.log(obj.data);
                            var checkedData = obj.data; // 获取选中的节点数据
                            checkedIds.push(checkedData.id); // 将选中节点的 id 添加到数组中
                            checkedIdsAll = [...new Set(checkedIds)]
                            if (obj.checked === false) {
                                // 找需要删除的数值删除
                                var uncheckedValue = obj.data.id // 假设数据中有 value 字段代表数值
                                var index = checkedIdsAll.indexOf(uncheckedValue); // 替换 yourValues 为存数值的数组
                                if (index !== -1) {
                                    checkedIdsAll.splice(index, 1); // 删除对应数值
                                    checkedIds = checkedIdsAll;
                                }
                            }
                        },
                    });
                }
            });

            //获取树形选中的id
            function getData(permissionId) {
                $.ajax({
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleGetRout/api/Menu/BackMenu?PermissionId=' + permissionId, // 后台接口地址
                    type: 'GET', // 请求方式，可以是 GET 或 POST
                    dataType: 'json', // 期望返回的数据类型
                    success: function (res) {
                        tree.reload('test');
                        tree.setChecked('test', res);
                    },
                    error: function (xhr, status, error) {
                        // 请求失败的回调函数
                        console.error(error); // 在控制台输出错误信息
                    }
                });
            }

            //反填
            function editData(permissionId, functionName) {
                $.ajax({
                    url: 'http://10.31.60.18:8000/AuthorizationPeopleGetRout/api/Menu/BackMenu?PermissionId=' + permissionId,
                    type: 'get',
                    contentType: 'application/json',
                    success: function (res) {
                        if (res != null) {
                            // 填充编辑数据
                            $("[name='permissionId']").val(permissionId);
                            $("#Id").text($("[name='permissionId']").val());
                            $("#BindId").text(functionName);
                            layer.open({

                                type: 1,
                                title: "修改新记录",
                                shift: 2,
                                area: ['360px', '500px'],
                                shade: 0,
                                shadeClose: false,
                                content: $("#add-main"),
                                success: function (layero, index) {
                                    layui.form.render(); // 重新渲染表单
                                }
                            });
                            getData(permissionId);
                        } else {
                            layer.msg(res.msg, { icon: 5 });
                        }
                    },
                    error: function (err) {
                        // 处理请求错误
                    }
                });
            }
        });





        //添加的弹出层
        var $ = layui.jquery;
        function onAddBtn() {
            $("#Id").text($("#functionName").val());
            $("#BindId").text($("#functionName option:selected").text());

            var laydate = layui.laydate;
            //渲染
            laydate.render({
                elem: '#storageDate'
            });

            layer.open({
                type: 1,
                title: "添加功能信息",
                closeBtn: false,
                shift: 12,
                area: ['360px', '600px'],
                shade: 0,
                shadeClose: false,
                content: $("#add-main"),
                success: function (layero, index) {

                }
            });
        }
    </script>
</div>
<script type="text/html" id="barDemo">
    <div class="layui-btn-container">
        <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit">修改</i></a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
    </div>
</script>
